package com.imooc.bilibili.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imooc.bilibili.constant.common.CommonConstant;
import com.imooc.bilibili.constant.rocket.UserMomentsConstant;
import com.imooc.bilibili.domain.user.UserMoment;
import com.imooc.bilibili.mapper.user.UserMomentsMapper;
import com.imooc.bilibili.user.service.UserMomentsService;
import com.imooc.bilibili.util.StringUtils;
import com.imooc.bilibili.util.json.JsonUtils;
import com.imooc.bilibili.util.redis.RedisUtils;
import com.imooc.bilibili.util.rocket.RocketMQUtils;
import com.imooc.bilibili.util.spring.SpringUtils;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 用户动态ServiceImpl
 *
 * @author gcq
 * @Create 2022-05-29
 */
@Service
public class UserMomentsServiceImpl extends ServiceImpl<UserMomentsMapper, UserMoment> implements UserMomentsService {


    @Autowired
    private UserMomentsMapper userMomentsMapper;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Integer addUserMoments(UserMoment userMoment) throws MQBrokerException, RemotingException, InterruptedException, MQClientException, UnsupportedEncodingException {
        userMoment.setCreateTime(new Date());
        userMomentsMapper.insert(userMoment);
        // 将动态发送到MQ中
        DefaultMQProducer producer = SpringUtils.getBean("momentsProducer");
        Message message = new Message(UserMomentsConstant.TOPIC_MOMENTS, JsonUtils.objectToJson(userMoment).getBytes(CommonConstant.UTF_8));
        RocketMQUtils.syncSendMsg(producer, message);
        return CommonConstant.SAVE_SUCCESS;
    }

    @Override
    public List<UserMoment> getUserSubscribedMoments(Long userId) {
        String key = "subscribed-" + userId;
        String listStr = redisUtils.get(key);
        if(StringUtils.isEmpty(listStr)) {
            return Collections.emptyList();
        }
        return JsonUtils.jsonToList(listStr, UserMoment.class);
    }
}